package com.abl.tomcat.mapper;

import com.abl.tomcat.util.FileKit;
import com.abl.tomcat.util.LogKit;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class Mapper {

    //<ServletName,Class路径>
    private static final HashMap<String, String> nameClass = new HashMap<>();
    //<ServletName,请求地址>
    private static final HashMap<String, String> nameUrl = new HashMap<>();
    //<请求地址,Class路径>
    private static final HashMap<String, String> urlClass = new HashMap<>();
    //<请求地址,ServletName>
    private static final HashMap<String, String> urlName = new HashMap<>();

    /**
     * 扫描全部 Servlet
     */
    public static void scanServlet() throws Exception {
        //TODO 解析web.xml
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(FileKit.getResourceAsStream("/web.xml"));

        //<ServletName,Class路径>
        List<Element> servlet = document.selectNodes("/web-app/servlet");
        for (Element e : servlet) {
            Node name_ = e.selectSingleNode("servlet-name");
            Node class_ = e.selectSingleNode("servlet-class");
            nameClass.put(name_.getStringValue(), class_.getStringValue());
        }

        //<ServletName,请求地址>
        List<Element> mapping = document.selectNodes("/web-app/servlet-mapping");
        for (Element e : mapping) {
            Node name_ = e.selectSingleNode("servlet-name");
            Node url_ = e.selectSingleNode("url-pattern");
            nameUrl.put(name_.getStringValue(), url_.getStringValue());
        }

        //<请求地址,Class路径>
        //<请求地址,ServletName>
        Set<String> strings = nameUrl.keySet();
        for (String name : strings) {
            String url_ = nameUrl.get(name);
            String class_ = nameClass.get(name);
            if (url_ == null || class_ == null || url_.isBlank() || class_.isBlank())
                throw new Exception("web.xml，servlet配置错误，请检查。");
            urlClass.put(url_, class_);
            urlName.put(url_, name);
        }
        LogKit.info("扫描全部 Servlet 完成");
    }

    //返回类路径
    public static String getServletClass(String url) {
        return urlClass.get(url);
    }

}
